﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using IDesktop.Core;
using IDesktop.View;

namespace IDesktop
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private IDesktopCore _core;
        private DispatcherTimer _coreTimer;
        private DispatcherTimer _hourFlipTimer;
        private DispatcherTimer _minuteFlipTimer;
        private DispatcherTimer _weatherTimer;
        private DateTime _currentTime = DateTime.Now;
        private DateTime _lastTime;
        private Dictionary<string, string> _currentImage;
        private int _hourFrame = 0;
        private int _minuteFrame = 0;
        private SetupWindow _setupWindow;
        private string _cityName;
        private string _cityID;
        private string _savePath;
        private WeatherInfo _weatherInfo;
        private FutureWeatherInfo _futureWeatherInfo;
        private static ChineseLunisolarCalendar _chineseDate = new ChineseLunisolarCalendar();
        private double _weatherUpdateInterval = 30.0;
        private NotifyIcon _notifyIcon;
        private IntPtr _parentHandle;
        private ToolStripMenuItem _menuItem_Lock;
        private ToolStripMenuItem _menuItem_UnLock;
        private ToolStripMenuItem _menuItem_CaptureScreen;
        private ToolStripMenuItem _menuItem_SendSNS;
        private ToolStripMenuItem _menuItem_Exit;

        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 每秒钟定时刷新界面
        /// </summary>
        private void Refresh(object sender, EventArgs e)
        {

            _currentTime = DateTime.Now;
            if (_lastTime.Hour != _currentTime.Hour)
            {
                hourFlip.Visibility = Visibility.Visible;
                leftHourFlipTop.Visibility = Visibility.Visible;
                leftHourFlipBottom.Visibility = Visibility.Visible;
                rightHourFlipTop.Visibility = Visibility.Visible;
                rightHourFlipBottom.Visibility = Visibility.Visible;
                _hourFlipTimer.Start();
            }
            if (_lastTime.Minute != _currentTime.Minute)
            {

                minuteFlip.Visibility = Visibility.Visible;
                leftMinuteFlipTop.Visibility = Visibility.Visible;
                leftMinuteFlipBottom.Visibility = Visibility.Visible;
                rightMinuteFlipTop.Visibility = Visibility.Visible;
                rightMinuteFlipBottom.Visibility = Visibility.Visible;
                _minuteFlipTimer.Start();
            }
            _lastTime = _currentTime;
        }

        /// <summary>
        /// 时间改变的动画效果
        /// </summary>
        private void HourAnimate(object sender, EventArgs e)
        {
            DigitalZone zone = DigitalZone.HourTens | DigitalZone.HourUnits;
            SetCurrentImage(zone);
            hourFlip.Source = new BitmapImage(new Uri(string.Format("/IDesktop;component/Resource/FlipAnim/Background/{0}.png", _hourFrame), UriKind.Relative));

            #region 数字的扭曲与缩放
            switch (_hourFrame)
            {
                case 0:
                    leftHourTopScale.ScaleY = 1.0;
                    rightHourTopScale.ScaleY = 1.0;

                    leftHourTopSkew.AngleX = 0.0;
                    rightHourTopSkew.AngleX = 0.0;
                    break;
                case 1:
                    leftHourTopScale.ScaleY = 1.1;
                    rightHourTopScale.ScaleY = 1.1;

                    leftHourTopSkew.AngleX = 1.0;
                    rightHourTopSkew.AngleX = 1.0;
                    break;
                case 2:
                    leftHourTopScale.ScaleY = 1.0;
                    rightHourTopScale.ScaleY = 1.0;

                    leftHourTopSkew.AngleX = 3.0;
                    rightHourTopSkew.AngleX = 3.0;
                    break;
                case 3:
                    leftHourTopScale.ScaleY = 0.9;
                    rightHourTopScale.ScaleY = 0.9;

                    leftHourTopSkew.AngleX = 6.0;
                    rightHourTopSkew.AngleX = 6.0;
                    break;
                case 4:
                    leftHourTopScale.ScaleY = 0.8;
                    rightHourTopScale.ScaleY = 0.8;

                    leftHourTopSkew.AngleX = 10.0;
                    rightHourTopSkew.AngleX = 10.0;
                    break;
                case 5:
                    leftHourTopScale.ScaleY = 0.7;
                    rightHourTopScale.ScaleY = 0.7;

                    leftHourTopSkew.AngleX = 15.0;
                    rightHourTopSkew.AngleX = 15.0;
                    break;
                case 6:
                    leftHourTopScale.ScaleY = 0.6;
                    rightHourTopScale.ScaleY = 0.6;

                    leftHourTopSkew.AngleX = 21.0;
                    rightHourTopSkew.AngleX = 21.0;
                    break;
                case 7:
                    leftHourTopScale.ScaleY = 0.5;
                    rightHourTopScale.ScaleY = 0.5;

                    leftHourTopSkew.AngleX = 28.0;
                    rightHourTopSkew.AngleX = 28.0;
                    break;
                case 8:
                    leftHourTopScale.ScaleY = 0.35;
                    rightHourTopScale.ScaleY = 0.35;

                    leftHourTopSkew.AngleX = 29.0;
                    rightHourTopSkew.AngleX = 29.0;
                    break;
                case 9:
                    leftHourTopScale.ScaleY = 0.25;
                    rightHourTopScale.ScaleY = 0.25;

                    leftHourTopSkew.AngleX = 30.0;
                    rightHourTopSkew.AngleX = 30.0;
                    break;
                case 10:
                    leftHourTopScale.ScaleY = 0.1;
                    rightHourTopScale.ScaleY = 0.1;

                    leftHourTopSkew.AngleX = 30.0;
                    rightHourTopSkew.AngleX = 30.0;
                    break;
                case 11:
                    leftHourTopScale.ScaleY = 0.0;
                    rightHourTopScale.ScaleY = 0.0;

                    leftHourTopSkew.AngleX = 30.0;
                    rightHourTopSkew.AngleX = 30.0;

                    break;
                case 12:
                    leftHourBottomScale.ScaleY = 0.1;
                    rightHourBottomScale.ScaleY = 0.1;

                    leftHourBottomSkew.AngleX = -30.0;
                    rightHourBottomSkew.AngleX = -30.0;
                    break;
                case 13:
                    leftHourBottomScale.ScaleY = 0.25;
                    rightHourBottomScale.ScaleY = 0.25;

                    leftHourBottomSkew.AngleX = -30.0;
                    rightHourBottomSkew.AngleX = -30.0;
                    break;
                case 14:
                    leftHourBottomScale.ScaleY = 0.35;
                    rightHourBottomScale.ScaleY = 0.35;

                    leftHourBottomSkew.AngleX = -30.0;
                    rightHourBottomSkew.AngleX = -30.0;
                    break;
                case 15:
                    leftHourBottomScale.ScaleY = 0.5;
                    rightHourBottomScale.ScaleY = 0.5;

                    leftHourBottomSkew.AngleX = -29.0;
                    rightHourBottomSkew.AngleX = -29.0;
                    break;
                case 16:
                    leftHourBottomScale.ScaleY = 0.6;
                    rightHourBottomScale.ScaleY = 0.6;

                    leftHourBottomSkew.AngleX = -28.0;
                    rightHourBottomSkew.AngleX = -28.0;
                    break;
                case 17:
                    leftHourBottomScale.ScaleY = 0.7;
                    rightHourBottomScale.ScaleY = 0.7;

                    leftHourBottomSkew.AngleX = -21.0;
                    rightHourBottomSkew.AngleX = -21.0;
                    break;
                case 18:
                    leftHourBottomScale.ScaleY = 0.8;
                    rightHourBottomScale.ScaleY = 0.8;

                    leftHourBottomSkew.AngleX = -15.0;
                    rightHourBottomSkew.AngleX = -15.0;
                    break;
                case 19:
                    leftHourBottomScale.ScaleY = 0.9;
                    rightHourBottomScale.ScaleY = 0.9;

                    leftHourBottomSkew.AngleX = -10.0;
                    rightHourBottomSkew.AngleX = -10.0;
                    break;
                case 20:
                    leftHourBottomScale.ScaleY = 1.0;
                    rightHourBottomScale.ScaleY = 1.0;

                    leftHourBottomSkew.AngleX = -6.0;
                    rightHourBottomSkew.AngleX = -6.0;
                    break;
                case 21:
                    hourFlip.Visibility = Visibility.Hidden;
                    leftHourFlipTop.Visibility = Visibility.Hidden;
                    leftHourFlipBottom.Visibility = Visibility.Hidden;
                    rightHourFlipTop.Visibility = Visibility.Hidden;
                    rightHourFlipBottom.Visibility = Visibility.Hidden;
                    _hourFrame = 0;
                    _hourFlipTimer.Stop();
                    return;
            }
            #endregion

            _hourFrame++;
        }

        /// <summary>
        /// 时间改变的动画效果
        /// </summary>
        private void MinuteAnimate(object sender, EventArgs e)
        {
            DigitalZone zone = DigitalZone.MinuteTens | DigitalZone.MinuteUnits;
            SetCurrentImage(zone);
            minuteFlip.Source = new BitmapImage(new Uri(string.Format("/IDesktop;component/Resource/FlipAnim/Background/{0}.png", _minuteFrame), UriKind.Relative));

            #region 数字的扭曲与缩放
            switch (_minuteFrame)
            {
                case 0:
                    leftMinuteTopScale.ScaleY = 1.0;
                    rightMinuteTopScale.ScaleY = 1.0;

                    leftMinuteTopSkew.AngleX = 0.0;
                    rightMinuteTopSkew.AngleX = 0.0;
                    break;
                case 1:
                    leftMinuteTopScale.ScaleY = 1.1;
                    rightMinuteTopScale.ScaleY = 1.1;

                    leftMinuteTopSkew.AngleX = 1.0;
                    rightMinuteTopSkew.AngleX = 1.0;
                    break;
                case 2:
                    leftMinuteTopScale.ScaleY = 1.0;
                    rightMinuteTopScale.ScaleY = 1.0;

                    leftMinuteTopSkew.AngleX = 3.0;
                    rightMinuteTopSkew.AngleX = 3.0;
                    break;
                case 3:
                    leftMinuteTopScale.ScaleY = 0.9;
                    rightMinuteTopScale.ScaleY = 0.9;

                    leftMinuteTopSkew.AngleX = 6.0;
                    rightMinuteTopSkew.AngleX = 6.0;
                    break;
                case 4:
                    leftMinuteTopScale.ScaleY = 0.8;
                    rightMinuteTopScale.ScaleY = 0.8;

                    leftMinuteTopSkew.AngleX = 10.0;
                    rightMinuteTopSkew.AngleX = 10.0;
                    break;
                case 5:
                    leftMinuteTopScale.ScaleY = 0.7;
                    rightMinuteTopScale.ScaleY = 0.7;

                    leftMinuteTopSkew.AngleX = 15.0;
                    rightMinuteTopSkew.AngleX = 15.0;
                    break;
                case 6:
                    leftMinuteTopScale.ScaleY = 0.6;
                    rightMinuteTopScale.ScaleY = 0.6;

                    leftMinuteTopSkew.AngleX = 21.0;
                    rightMinuteTopSkew.AngleX = 21.0;
                    break;
                case 7:
                    leftMinuteTopScale.ScaleY = 0.5;
                    rightMinuteTopScale.ScaleY = 0.5;

                    leftMinuteTopSkew.AngleX = 28.0;
                    rightMinuteTopSkew.AngleX = 28.0;
                    break;
                case 8:
                    leftMinuteTopScale.ScaleY = 0.35;
                    rightMinuteTopScale.ScaleY = 0.35;

                    leftMinuteTopSkew.AngleX = 29.0;
                    rightMinuteTopSkew.AngleX = 29.0;
                    break;
                case 9:
                    leftMinuteTopScale.ScaleY = 0.25;
                    rightMinuteTopScale.ScaleY = 0.25;

                    leftMinuteTopSkew.AngleX = 30.0;
                    rightMinuteTopSkew.AngleX = 30.0;
                    break;
                case 10:
                    leftMinuteTopScale.ScaleY = 0.1;
                    rightMinuteTopScale.ScaleY = 0.1;

                    leftMinuteTopSkew.AngleX = 30.0;
                    rightMinuteTopSkew.AngleX = 30.0;
                    break;
                case 11:
                    leftMinuteTopScale.ScaleY = 0.0;
                    rightMinuteTopScale.ScaleY = 0.0;

                    leftMinuteTopSkew.AngleX = 30.0;
                    rightMinuteTopSkew.AngleX = 30.0;

                    break;
                case 12:
                    leftMinuteBottomScale.ScaleY = 0.1;
                    rightMinuteBottomScale.ScaleY = 0.1;

                    leftMinuteBottomSkew.AngleX = -30.0;
                    rightMinuteBottomSkew.AngleX = -30.0;
                    break;
                case 13:
                    leftMinuteBottomScale.ScaleY = 0.25;
                    rightMinuteBottomScale.ScaleY = 0.25;

                    leftMinuteBottomSkew.AngleX = -30.0;
                    rightMinuteBottomSkew.AngleX = -30.0;
                    break;
                case 14:
                    leftMinuteBottomScale.ScaleY = 0.35;
                    rightMinuteBottomScale.ScaleY = 0.35;

                    leftMinuteBottomSkew.AngleX = -30.0;
                    rightMinuteBottomSkew.AngleX = -30.0;
                    break;
                case 15:
                    leftMinuteBottomScale.ScaleY = 0.5;
                    rightMinuteBottomScale.ScaleY = 0.5;

                    leftMinuteBottomSkew.AngleX = -29.0;
                    rightMinuteBottomSkew.AngleX = -29.0;
                    break;
                case 16:
                    leftMinuteBottomScale.ScaleY = 0.6;
                    rightMinuteBottomScale.ScaleY = 0.6;

                    leftMinuteBottomSkew.AngleX = -28.0;
                    rightMinuteBottomSkew.AngleX = -28.0;
                    break;
                case 17:
                    leftMinuteBottomScale.ScaleY = 0.7;
                    rightMinuteBottomScale.ScaleY = 0.7;

                    leftMinuteBottomSkew.AngleX = -21.0;
                    rightMinuteBottomSkew.AngleX = -21.0;
                    break;
                case 18:
                    leftMinuteBottomScale.ScaleY = 0.8;
                    rightMinuteBottomScale.ScaleY = 0.8;

                    leftMinuteBottomSkew.AngleX = -15.0;
                    rightMinuteBottomSkew.AngleX = -15.0;
                    break;
                case 19:
                    leftMinuteBottomScale.ScaleY = 0.9;
                    rightMinuteBottomScale.ScaleY = 0.9;

                    leftMinuteBottomSkew.AngleX = -10.0;
                    rightMinuteBottomSkew.AngleX = -10.0;
                    break;
                case 20:
                    leftMinuteBottomScale.ScaleY = 1.0;
                    rightMinuteBottomScale.ScaleY = 1.0;

                    leftMinuteBottomSkew.AngleX = -6.0;
                    rightMinuteBottomSkew.AngleX = -6.0;
                    break;
                case 21:
                    minuteFlip.Visibility = Visibility.Hidden;
                    leftMinuteFlipTop.Visibility = Visibility.Hidden;
                    leftMinuteFlipBottom.Visibility = Visibility.Hidden;
                    rightMinuteFlipTop.Visibility = Visibility.Hidden;
                    rightMinuteFlipBottom.Visibility = Visibility.Hidden;
                    _minuteFrame = 0;
                    _minuteFlipTimer.Stop();
                    return;
            }
            #endregion

            _minuteFrame++;
        }

        /// <summary>
        /// 设置当前时间对应的图片
        /// </summary>
        /// <param name="zone">时间区域</param>
        private void SetCurrentImage(DigitalZone zone)
        {
            if (zone == DigitalZone.Hour)
            {
                _currentImage = _core.GetCurrentImage(_currentTime, zone);
                leftHourTop.Source = new BitmapImage(new Uri(string.Format(_currentImage["HourTens"], "1"), UriKind.Relative));
                leftHourBottom.Source = new BitmapImage(new Uri(string.Format(_currentImage["HourTens"], "2"), UriKind.Relative));

                rightHourTop.Source = new BitmapImage(new Uri(string.Format(_currentImage["HourUnits"], "1"), UriKind.Relative));
                rightHourBottom.Source = new BitmapImage(new Uri(string.Format(_currentImage["HourUnits"], "2"), UriKind.Relative));

                leftHourFlipTop.Source = new BitmapImage(new Uri(string.Format(_currentImage["HourTens"], "1"), UriKind.Relative));
                leftHourFlipBottom.Source = new BitmapImage(new Uri(string.Format(_currentImage["HourTens"], "2"), UriKind.Relative));

                rightHourFlipTop.Source = new BitmapImage(new Uri(string.Format(_currentImage["HourUnits"], "1"), UriKind.Relative));
                rightHourFlipBottom.Source = new BitmapImage(new Uri(string.Format(_currentImage["HourUnits"], "2"), UriKind.Relative));

            }
            else if (zone == DigitalZone.Minute)
            {
                _currentImage = _core.GetCurrentImage(_currentTime, zone);
                leftMinuteTop.Source = new BitmapImage(new Uri(string.Format(_currentImage["MinuteTens"], "1"), UriKind.Relative));
                leftMinuteBottom.Source = new BitmapImage(new Uri(string.Format(_currentImage["MinuteTens"], "2"), UriKind.Relative));

                rightMinuteTop.Source = new BitmapImage(new Uri(string.Format(_currentImage["MinuteUnits"], "1"), UriKind.Relative));
                rightMinuteBottom.Source = new BitmapImage(new Uri(string.Format(_currentImage["MinuteUnits"], "2"), UriKind.Relative));

                leftMinuteFlipTop.Source = new BitmapImage(new Uri(string.Format(_currentImage["MinuteTens"], "1"), UriKind.Relative));
                leftMinuteFlipBottom.Source = new BitmapImage(new Uri(string.Format(_currentImage["MinuteTens"], "2"), UriKind.Relative));

                rightMinuteFlipTop.Source = new BitmapImage(new Uri(string.Format(_currentImage["MinuteUnits"], "1"), UriKind.Relative));
                rightMinuteFlipBottom.Source = new BitmapImage(new Uri(string.Format(_currentImage["MinuteUnits"], "2"), UriKind.Relative));

            }
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        private void UpdateWeather(object sender, EventArgs e)
        {
            RefershWeather();
        }

        private void RefershWeather()
        {
            try
            {
                ///
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    _cityID = Config.Read("CityCode");
                    _cityName = Config.Read("CityName");
                    if (!string.IsNullOrEmpty(_cityID) && !string.IsNullOrEmpty(_cityName))
                    {
                        Weather weather = new Weather("", "http://www.weather.com.cn/data/cityinfo/{0}.html", "");
                        _weatherInfo = weather.GetWeather(_cityID, _cityName);
                        city.Text = _weatherInfo.Name;
                        this.weather.Text = (Timeline.GetTimeline() == TimeDivision.Day) ? _weatherInfo.DayWeather : _weatherInfo.NightWeather;
                        temperature.Text = (Timeline.GetTimeline() == TimeDivision.Day) ? _weatherInfo.DayTemperature : _weatherInfo.NightTemperature;
                        string imgNO = "na";
                        WeatherType weatherType;
                        if (Enum.TryParse<WeatherType>(_weatherInfo.DayWeather.Replace("-", "_"), out weatherType))
                        {
                            imgNO = ((int)weatherType).ToString();
                        }
                        weatherControl.ImageSource = new BitmapImage(new Uri(string.Format("/IDesktop;Component/Resource/Weather/{0}.png", imgNO), UriKind.Relative));
                    }
                    date.Text = DateTime.Now.ToString("MM\\/dd dddd");
                    chineseDate.Text = ChinaDate.GetShortChinaDate(_currentTime);
                }), null);

                //更新未来6天内的天气
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    _cityID = Config.Read("CityCode");
                    _cityName = Config.Read("CityName");
                    if (!string.IsNullOrEmpty(_cityID) && !string.IsNullOrEmpty(_cityName))
                    {
                        Weather weather = new Weather("", "", "http://m.weather.com.cn/data/{0}.html");
                        _futureWeatherInfo = weather.GetFutureWeather(_cityID, _cityName);
                        WeatherInfo weatherInfo = new WeatherInfo();

                        //first day
                        weatherInfo.DayWeather = _futureWeatherInfo.Weather1;
                        weatherInfo.DayTemperature = _futureWeatherInfo.Temp1;
                        SetFutureWeather(firstDay, weatherInfo);

                        //second day
                        weatherInfo.DayWeather = _futureWeatherInfo.Weather2;
                        weatherInfo.DayTemperature = _futureWeatherInfo.Temp2;
                        SetFutureWeather(secondDay, weatherInfo);

                        //third day
                        weatherInfo.DayWeather = _futureWeatherInfo.Weather3;
                        weatherInfo.DayTemperature = _futureWeatherInfo.Temp3;
                        SetFutureWeather(thirdDay, weatherInfo);

                        //fourth day
                        weatherInfo.DayWeather = _futureWeatherInfo.Weather4;
                        weatherInfo.DayTemperature = _futureWeatherInfo.Temp4;
                        SetFutureWeather(fourthDay, weatherInfo);

                        //fifth day
                        weatherInfo.DayWeather = _futureWeatherInfo.Weather5;
                        weatherInfo.DayTemperature = _futureWeatherInfo.Temp5;
                        SetFutureWeather(fifthDay, weatherInfo);

                        //sixth day
                        weatherInfo.DayWeather = _futureWeatherInfo.Weather6;
                        weatherInfo.DayTemperature = _futureWeatherInfo.Temp6;
                        SetFutureWeather(sixthDay, weatherInfo);
                    }
                }));
            }
            catch (Exception)
            {
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (Config.Read("NeverShow") == "False")
            {
                this.Setup();
            }
            else
            {
                RefershWeather();
            }
        }

        private void Window_Initialized(object sender, EventArgs e)
        {
            _core = new IDesktopCore();
            _coreTimer = new DispatcherTimer();
            _coreTimer.Interval = TimeSpan.FromSeconds(1.0);
            _coreTimer.Tick += new EventHandler(Refresh);
            _coreTimer.Start();

            _hourFlipTimer = new DispatcherTimer();
            _hourFlipTimer.Interval = TimeSpan.FromMilliseconds(50);
            _hourFlipTimer.Tick += new EventHandler(HourAnimate);

            _minuteFlipTimer = new DispatcherTimer();
            _minuteFlipTimer.Interval = TimeSpan.FromMilliseconds(50);
            _minuteFlipTimer.Tick += new EventHandler(MinuteAnimate);

            _weatherTimer = new DispatcherTimer();
            _weatherTimer.Interval = TimeSpan.FromMinutes(_weatherUpdateInterval);
            _weatherTimer.Tick += new EventHandler(UpdateWeather);


            _notifyIcon = new NotifyIcon();
            ContextMenuStrip contextMenuStrip = new ContextMenuStrip();
            _notifyIcon.ContextMenuStrip = contextMenuStrip;

            //关于
            ToolStripMenuItem menuItem_About = new ToolStripMenuItem("关于");
            contextMenuStrip.Items.Add(menuItem_About);

            //锁定到桌面
            _menuItem_Lock = new ToolStripMenuItem("锁定到桌面");
            _menuItem_Lock.Click += new EventHandler(MenuItem_Lock_Click);
            contextMenuStrip.Items.Add(_menuItem_Lock);

            //从桌面解锁
            _menuItem_UnLock = new ToolStripMenuItem("从桌面解锁");
            _menuItem_UnLock.Visible = false;
            _menuItem_UnLock.Click += new EventHandler(MenuItem_UnLock_Click);
            contextMenuStrip.Items.Add(_menuItem_UnLock);

            //分享当前天气到新浪微博
            _menuItem_SendSNS = new ToolStripMenuItem("分享到");
            _menuItem_SendSNS.Click += new EventHandler(_menuItem_SendSNS_Click);
            contextMenuStrip.Items.Add(_menuItem_SendSNS);

            //截图
            _menuItem_CaptureScreen = new ToolStripMenuItem("截屏");
            _menuItem_CaptureScreen.Click += new EventHandler(_menuItem_CaptureScreen_Click);
            contextMenuStrip.Items.Add(_menuItem_CaptureScreen);

            //退出
            _menuItem_Exit = new ToolStripMenuItem("退出");
            _menuItem_Exit.Click += new EventHandler(MenuItem_Exit_Click);
            contextMenuStrip.Items.Add(_menuItem_Exit);

            //_notifyIcon.MouseClick += new System.Windows.Forms.MouseEventHandler(NotifyIcon_MouseClick);
            System.Drawing.Icon icon = IDesktop.Properties.Resources.app;
            _notifyIcon.Icon = icon;
            _notifyIcon.Text = "NotifyIcon Test";
            _notifyIcon.Visible = true;

            _parentHandle = (new WindowInteropHelper(this)).Owner;
        }

        private void WeatherControl_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.Setup();
        }

        private void SetFutureWeather(WeatherControl weatherControl, WeatherInfo weatherInfo)
        {
            string imgNO = "na";
            WeatherType weatherType;
            if (Enum.TryParse<WeatherType>(_weatherInfo.DayWeather.Replace("-", "_"), out weatherType))
            {
                imgNO = ((int)weatherType).ToString();
            }

            weatherControl.weatherPic.Source = new BitmapImage(new Uri(string.Format("/IDesktop;Component/Resource/Weather/{0}.png", imgNO), UriKind.Relative));
            weatherControl.weather.Text = (Timeline.GetTimeline() == TimeDivision.Day) ? weatherInfo.DayWeather : weatherInfo.NightWeather;
            weatherControl.temperature.Text = (Timeline.GetTimeline() == TimeDivision.Day) ? weatherInfo.DayTemperature : weatherInfo.NightTemperature;
            weatherControl.weather.Visibility = Visibility.Visible;
            weatherControl.temperature.Visibility = Visibility.Visible;
        }

        private void NotifyIcon_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                MethodInfo methodInfo = typeof(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.Instance | BindingFlags.NonPublic);
                methodInfo.Invoke(_notifyIcon, null);
            }
        }

        private void MenuItem_Lock_Click(object sender, EventArgs e)
        {
            IntPtr handle = GetDesktopHandle();
            IntPtr application = (new WindowInteropHelper(this)).Handle;

            const int HWND_TOP = 0x0000;
            const int SWP_FRAMECHANGED = 0x0020;

            IntPtr hWndInsertAfter = new IntPtr(HWND_TOP);
            Win32Support.SetWindowPos(new HandleRef(this, application), new HandleRef(this, hWndInsertAfter), Screen.PrimaryScreen.Bounds.Right - (int)this.Width, 0, (int)this.Width, (int)this.Height, SWP_FRAMECHANGED);

            Win32Support.SetWindowLong((new WindowInteropHelper(this)).Handle, Win32Support.GWL_HWNDPARENT, handle);
            //Win32Support.SetParent(application, handle);

            HwndSource source = HwndSource.FromHwnd(application);
            source.AddHook(new HwndSourceHook(WndProc));

            _menuItem_Lock.Visible = false;
            _menuItem_UnLock.Visible = true;
        }

        private void MenuItem_UnLock_Click(object sender, EventArgs e)
        {
            IntPtr application = (new WindowInteropHelper(this)).Handle;

            Win32Support.SetWindowLong((new WindowInteropHelper(this)).Handle, Win32Support.GWL_HWNDPARENT, _parentHandle);

            HwndSource source = HwndSource.FromHwnd(application);
            source.RemoveHook(new HwndSourceHook(WndProc));

            _menuItem_UnLock.Visible = false;
            _menuItem_Lock.Visible = true;
        }

        private void MenuItem_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            int command = wParam.ToInt32() & 0xfff0;
            switch (msg)
            {
                case 0x0112:
                    if (command == 0xF010)
                    {
                        handled = true;
                    }
                    break;
                //WM_LBUTTONDBLCLK
                case 0x0203:
                    this.Setup();
                    handled = false;
                    break;
                //WM_LBUTTONDOWN 
                case 0x0201:
                    handled = false;
                    break;
                //
                default:
                    break;
            }
            return IntPtr.Zero;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                _menuItem_Lock.Dispose();
                _menuItem_UnLock.Dispose();
                _notifyIcon.Dispose();
            }
            catch (Exception)
            {
            }
        }

        private void Setup()
        {
            _setupWindow = new SetupWindow();
            _setupWindow.EventHandler += new SetupWindow.RefreshConfigEventHandler(RefershWeather);
            _setupWindow.Owner = this;
            _setupWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            _setupWindow.ShowDialog();
        }

        private IntPtr GetDesktopHandle()
        {
            IntPtr result = IntPtr.Zero;
            IntPtr handle = IntPtr.Zero;

            handle = Win32Support.FindWindowEx(IntPtr.Zero, IntPtr.Zero, "WorkerW", "");
            while (result == IntPtr.Zero)
            {
                result = Win32Support.FindWindowEx(handle, IntPtr.Zero, "SHELLDLL_DefView", "");
                handle = Win32Support.FindWindowEx(IntPtr.Zero, handle, "WorkerW", "");
            }

            result = Win32Support.FindWindowEx(result, IntPtr.Zero, "SysListView32", "FolderView");

            return result;
        }

        private void _menuItem_CaptureScreen_Click(object sender, EventArgs e)
        {
            string id = Guid.NewGuid().ToString();
            string savePath = string.Empty;
            string tmpPath = AppDomain.CurrentDomain.BaseDirectory + "/ScreenShot";
            string fileName = string.Empty;

            if (string.IsNullOrEmpty(_savePath))
            {
                savePath = Config.Read("SavePath");
                _savePath = savePath;
            }
            if (string.IsNullOrEmpty(savePath))
            {
                savePath = tmpPath;
            }

            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            fileName = Path.Combine(savePath, id + ".png");
            File.WriteAllBytes(fileName, ExtenClass.GetPNGImage(WND, 1.0));
            MessageBoxResult result = System.Windows.MessageBox.Show("截图已保存！\r\n" + fileName + "\r\n是否打开存放地址", "提示", MessageBoxButton.YesNo);
            if (MessageBoxResult.Yes == result)
            {
                Process.Start("explorer.exe", "/e, /select," + Path.GetFullPath(fileName));
            }
        }


        private void _menuItem_SendSNS_Click(object sender, EventArgs e)
        {
            byte[] imgBuffer = ExtenClass.GetPNGImage(WND, 1.0);
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.StreamSource = new MemoryStream(imgBuffer);
            bi.EndInit();

            NO.I.MainWindow publishWindow = new NO.I.MainWindow();
            publishWindow.ImageBuffer = imgBuffer;
            publishWindow.ImageSource = bi;
            publishWindow.insert_Image.Visibility = Visibility.Hidden;

            publishWindow.Show();
        }
    }

    static class ExtenClass
    {

        /// Gets a bmp "screenshot" of the current UIElement
        /// UIElement to screenshot
        /// Scale to render the screenshot
        /// Byte array of bmp data
        public static byte[] GetPNGImage(this UIElement source, double scale)
        {
            double actualHeight = source.RenderSize.Height;
            double actualWidth = source.RenderSize.Width;

            double renderHeight = actualHeight * scale;
            double renderWidth = actualWidth * scale;

            RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32);
            VisualBrush sourceBrush = new VisualBrush(source);
            sourceBrush.Opacity = 1;

            DrawingVisual drawingVisual = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();


            using (drawingContext)
            {
                drawingContext.PushTransform(new ScaleTransform(scale, scale));
                drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(renderWidth, renderHeight)));
            }

            renderTarget.Render(drawingVisual);

            PngBitmapEncoder pngEncoder = new PngBitmapEncoder();

            pngEncoder.Frames.Add(BitmapFrame.Create(renderTarget));



            Byte[] _imageArray;

            using (MemoryStream outputStream = new MemoryStream())
            {
                pngEncoder.Save(outputStream);
                _imageArray = outputStream.ToArray();
            }

            return _imageArray;
        }
    }
}
